package br.com.caelum.vraptor.blank;


import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServlet;

import org.apache.tomcat.util.http.fileupload.IOUtils;

import br.com.caelum.vraptor.interceptor.multipart.UploadedFile;
import br.com.caelum.vraptor.ioc.Component;

@Component
public class Atualizacao extends HttpServlet implements Serializable{
	
	private static final long serialVersionUID = 1L;
	private File pastaPlanilhas;
	private String caminhoFinalArquivo;
	
	public String getCaminhoFinalArquivo() {
		return caminhoFinalArquivo;
	}

	public void setCaminhoFinalArquivo(String caminhoFinalArquivo) {
		this.caminhoFinalArquivo = caminhoFinalArquivo;
	}
	
	public Atualizacao(ServletContext context) {
		String caminhoPlanilhas = context.getRealPath("/WEB-INF/pdf");
		pastaPlanilhas = new File(caminhoPlanilhas);
		pastaPlanilhas.setReadable(true);
		pastaPlanilhas.setWritable(true);
		pastaPlanilhas.mkdir();
	}
	
	public boolean save(UploadedFile planilha) {
		File arquivo = new File(pastaPlanilhas, planilha.getFileName());
		try {
			IOUtils.copy(planilha.getFile(), new FileOutputStream(arquivo));
			setCaminhoFinalArquivo(arquivo.getPath());
			return true;
		}catch (FileNotFoundException ex){
			ex.printStackTrace();
			return false;
		}catch (IOException e) {
			e.printStackTrace();
			return false;
		} 
	}
	
	
	public List<Pdf> lista(){
		File diretorio = new File(pastaPlanilhas.getAbsolutePath());
		File flist[] = diretorio.listFiles();
		List<Pdf> listapdf = new ArrayList<Pdf>();	
		Pdf pdf = null;
		
		for ( int i = 0; i < flist.length; i++ ){
			pdf  = new Pdf();
			pdf.setCaminho(flist[i].getAbsolutePath());
			pdf.setNome(flist[i].getName());
			pdf.setPosicao(i);
			pdf.setData(new Date(flist[i].lastModified()));
			listapdf.add(pdf);			
		}
		
		return listapdf;			
	}
	
	public void delete(int posicao){
		List<Pdf> lista = lista();
		File file = new File(lista.get(posicao).getCaminho());
		file.delete();
	}
	
	public Pdf findById(int posicao){
		List<Pdf> lista = lista();
		return lista.get(posicao);
	}

}